﻿using PLCSharp.CoreModel.Prism;
using PLCSharp.Views.Connects;
using PLCSharp.Views.Vision.Camera;
using Prism.Commands;
using Prism.Dialogs;
using Prism.Events;
using Prism.Ioc;
using System.Collections.ObjectModel;

namespace PLCSharp.Views.Vision
{
    [Model]
    public class VisionsModel : ModelBase
    {
        public VisionsModel(IContainerExtension container, IEventAggregator ea, IDialogService dialogService) : base(container, ea, dialogService)
        {
            Connects = container.Resolve<ConnectsModel>();
            Container = container;
            _HikCameras = container.Resolve<HikCameras>();
            _HikCameras.SearchCameras();
            foreach (var item in _DatasContext.Cameras)
            {

                switch (item.Brand)
                {
                    case CameraBrand.HikRobot:
                        var camera = _HikCameras.Cameras.Where(c => c.Name == item.Name).FirstOrDefault();
                        if (camera != null)
                        {
                            camera.Params = item.Params;
                            camera.ID = item.ID;
                            camera.Comment = item.Comment;
                            camera.Prompt = "";
                            Cameras.Add(camera);
                        }
                        else
                        {
                            Cameras.Add(item);
                            System.Windows.MessageBox.Show($"未发现相机{item.Name}，请检查连接");
                        }
                        break;

                }

            }
        }
        public IContainerExtension Container { get; set; }
        internal void SearchCameras()
        {
            CamerasAll.Clear();
            _HikCameras.SearchCameras();
            foreach (var item in _HikCameras.Cameras)
            {
                CamerasAll.Add(item);
            }
        }
        public ConnectsModel Connects { get; set; }

        private ObservableCollection<VisionFunction> _VisionFunctions = [];
        public ObservableCollection<VisionFunction> VisionFunctions
        {
            get { return _VisionFunctions; }
            set { SetProperty(ref _VisionFunctions, value); }
        }

        private VisionFunction _SelectedVisionFunction;
        /// <summary>
        /// 
        /// </summary>
        public VisionFunction SelectedVisionFunction
        {
            get { return _SelectedVisionFunction; }
            set { SetProperty(ref _SelectedVisionFunction, value); }
        }

        private DelegateCommand<string> _Manage;
        public DelegateCommand<string> Manage =>
            _Manage ??= new DelegateCommand<string>(ExecuteManage);

        void ExecuteManage(string cmd)
        {
            switch (cmd)
            {
                case "New":
                    var newFunction = new VisionFunction()
                    {
                        VisionsModel = this,
                        ImageDatas = ImageDatas,
                    };
                    VisionFunctions.Add(newFunction);

                    break;
                case "Remove":
                    if (SelectedVisionFunction != null)
                    {
                        var visionFunction = _DatasContext.VisionFunctions.Where(c => c.ID == SelectedVisionFunction.ID).FirstOrDefault();
                        if (visionFunction != null)
                        {
                            _DatasContext.VisionFunctions.Remove(visionFunction); 
                            _DatasContext.Save();
                        }
                        var name = SelectedVisionFunction.Name;
                        VisionFunctions.Remove(SelectedVisionFunction);
                        SendErr($"已删除：{name}", ErrType.ShowDialog);
                      
                    }
                    break;
                case "Save":
                    var names = new List<string>();

                    foreach (var item in VisionFunctions)
                    {
                        if (string.IsNullOrEmpty(item.Name))
                        {
                            SendErr($"保存失败，名称{item.Name}不合适！", ErrType.ShowDialog);
                            return;
                        }

                        if (names.Contains(item.Name))
                        {
                            SendErr($"保存失败，重复的名称{item.Name}！", ErrType.ShowDialog);
                            return;
                        }
                        else
                        {
                            names.Add(item.Name);
                        }
                    }


                    foreach (var item in VisionFunctions)
                    {
                        if (_DatasContext.VisionFunctions.Any(h => h.ID == item.ID) == false)
                        {
                            item.RecipeID = _DatasContext.CurrentRecipe.ID;
                            var serializedVisionFlows = item.SerializedVisionFlows;
                            _DatasContext.VisionFunctions.Add(item);

                        }
                        else
                        {
                            var newitem = _DatasContext.VisionFunctions.Where(c => c.Name == item.Name).FirstOrDefault();
                            newitem.ID = item.ID;
                            newitem.RecipeID = item.RecipeID;
                            newitem.Name = item.Name;
                            newitem.Comment = item.Comment;
                            newitem.SerializedParams = item.SerializedParams;
                            newitem.SerializedVisionFlows = item.SerializedVisionFlows;

                        }


                    }
                    _DatasContext.Save();
                    SelectedVisionFunction.Prompt = "";

                    break;

                case "Config":

                    if (SelectedVisionFunction == null) return;
                    var dialogParams = new DialogParameters
                        {
                            { "SelectedVisionFunction", SelectedVisionFunction}
                        };

                    _dialogService.Show("VisionConfig", dialogParams, r =>
                {


                });

                    break;
            }
        }

        #region Camera
        private HikCameras _HikCameras;
        private ObservableCollection<CameraBase> _Cameras = [];
        public ObservableCollection<CameraBase> Cameras
        {
            get { return _Cameras; }
            set { SetProperty(ref _Cameras, value); }
        }

        private ObservableCollection<CameraBase> _CamerasAll = [];
        /// <summary>
        /// 
        /// </summary>
        public ObservableCollection<CameraBase> CamerasAll
        {
            get { return _CamerasAll; }
            set { SetProperty(ref _CamerasAll, value); }
        }
        private CameraBase _SelectedCamera;
        public CameraBase SelectedCamera
        {
            get { return _SelectedCamera; }
            set { SetProperty(ref _SelectedCamera, value); }
        }


        private DelegateCommand<string> _CamreraManage;
        public DelegateCommand<string> CamreraManage =>
            _CamreraManage ??= new DelegateCommand<string>(ExecuteCamreraManage);

        void ExecuteCamreraManage(string cmd)
        {
            switch (cmd)
            {
                case "New":

                    Cameras.Add(new CameraBase());

                    break;


                case "Save":
                    SaveCameras();
                    break;

                case "Config":
                    if (SelectedCamera != null)
                    {
                        var dialogParams = new DialogParameters
                        {
                            { "Camera", SelectedCamera }
                        };

                        _dialogService.Show("CameraConfig", dialogParams, r =>
                        {


                        });
                    }
                    break;

                case "Remove":
                    if (SelectedCamera != null)
                    {
                        var camera = _DatasContext.Cameras.Where(c => c.ID == SelectedCamera.ID).FirstOrDefault();
                        if (camera != null)
                        {
                            _DatasContext.Cameras.Remove(camera);
                            _DatasContext.Save();
                            var name = camera.Name;
                            Cameras.Remove(SelectedCamera);
                            SendErr($"已删除：{name}", ErrType.ShowDialog);
                        }
                    }
                    break;

            }

        }

        private void SaveCameras()
        {
            var names = new List<string>();

            foreach (var item in Cameras)
            {
                if (string.IsNullOrEmpty(item.Name))
                {
                    SendErr($"保存失败，名称{item.Name}不合适！", ErrType.ShowDialog);
                    return;
                }

                if (names.Contains(item.Name))
                {
                    SendErr($"保存失败，重复的名称{item.Name}！", ErrType.ShowDialog);
                    return;
                }
                else
                {
                    names.Add(item.Name);
                }
            }


            foreach (var item in Cameras)
            {
                if (!_DatasContext.Cameras.Any(h => h.ID == item.ID))
                {
                    _DatasContext.Cameras.Add(item);

                }
                else
                {
                    var camera = _DatasContext.Cameras.Where(c => c.Name == item.Name).FirstOrDefault();

                    camera.Params = item.Params;
                    camera.Comment = item.Comment;

                }


            }
            _DatasContext.Save();
            SelectedCamera.Prompt = "";

        }

        #endregion Camera

        #region 图像列表
        private ObservableCollection<ImageData> _ImageDatas = [];
        /// <summary>
        /// 
        /// </summary>
        public ObservableCollection<ImageData> ImageDatas
        {
            get { return _ImageDatas; }
            set { SetProperty(ref _ImageDatas, value); }
        }

        private ImageData _SelectImageData;
        /// <summary>
        /// 
        /// </summary>
        public ImageData SelectImageData
        {
            get { return _SelectImageData; }
            set { SetProperty(ref _SelectImageData, value); }
        }

        private DelegateCommand<string> _ImageManage;
        public DelegateCommand<string> ImageManage =>
            _ImageManage ??= new DelegateCommand<string>(ExecuteImageManage);

        void ExecuteImageManage(string cmd)
        {
            switch (cmd)
            {
                case "New":
                    var newImage = new ImageData()
                    {
                    };
                    ImageDatas.Add(newImage);

                    break;
                case "Remove":
                    if (SelectImageData != null)
                    {
                        var image = _DatasContext.ImageDatas.Where(c => c.ID == SelectedVisionFunction.ID).FirstOrDefault();
                        if (image != null)
                        {

                            _DatasContext.ImageDatas.Remove(image); 
                            _DatasContext.Save();
                        }
                        var name = SelectImageData.Name;
                        ImageDatas.Remove(SelectImageData);
                        SendErr($"已删除：{name}", ErrType.ShowDialog);
                    }
                    break;
                case "Save":
                    var names = new List<string>();

                    foreach (var item in ImageDatas)
                    {
                        if (string.IsNullOrEmpty(item.Name))
                        {
                            SendErr($"保存失败，名称{item.Name}不合适！", ErrType.ShowDialog);
                            return;
                        }

                        if (names.Contains(item.Name))
                        {
                            SendErr($"保存失败，重复的名称{item.Name}！", ErrType.ShowDialog);
                            return;
                        }
                        else
                        {
                            names.Add(item.Name);
                        }
                    }


                    foreach (var item in ImageDatas)
                    {
                        if (_DatasContext.ImageDatas.Any(h => h.ID == item.ID) == false)
                        {
                            item.RecipeID = _DatasContext.CurrentRecipe.ID;
                            _DatasContext.ImageDatas.Add(item);

                        }
                        else
                        {
                            var newitem = _DatasContext.ImageDatas.Where(c => c.Name == item.Name).FirstOrDefault();
                            newitem.ID = item.ID;
                            newitem.RecipeID = item.RecipeID;
                            newitem.Name = item.Name;
                            newitem.Comment = item.Comment;

                        }


                    }
                    SelectImageData.Prompt = "";
                    _DatasContext.Save();
                    break;
            }
        }



        #endregion
    }
}